import requests
import time  # 导入time模块以使用sleep函数


class ProxyIp:
    def __init__(self, secret="wth6gks2agsr2k1s", sign="502e4a5310ed76ce8b049fe1f8ecc698", num=1, type_='json', time=3, region=None):
        self.secret = secret
        self.sign = sign
        self.num = num
        self.type_ = type_
        self.time = time
        self.region = region

    def check_proxy(self, ip_port):
        """
        检查代理IP是否可用。
        """
        proxy_dict = {
            'http': f'http://{ip_port}',
            'https': f'https://{ip_port}'
        }
        try:
            response = requests.get('http://www.baidu.com', proxies=proxy_dict, timeout=5)
            if response.status_code == 200:
                print(f"Proxy {ip_port} is available.{response.status_code}")
                return True
            else:
                print(f"Proxy {ip_port} is not available.{response.status_code}")
                return False
        except requests.exceptions.RequestException:
            pass
        return False
    def tianqi_ip(self, max_retries=10):
        base_url = "http://api.tianqiip.com/getip?"
        params = {
            'secret': self.secret,
            'num': self.num,
            'type': self.type_,
            'time': self.time,
            'mr': 1,  # 默认值
            'sign': self.sign
        }
        if self.region is not None:
            params['region'] = self.region

        retries = 0
        while retries <= max_retries:
            url = base_url + '&'.join([f"{key}={value}" for key, value in params.items()])
            response = requests.get(url)
            # print(response.json())
            if response.status_code == 200:
                res = response.json()
                # print(res)
                if res['code'] == 1000:
                    ip_data = res['data'][0]  # 假设只处理第一个元素
                    ip_port = f"{ip_data['ip']}:{ip_data['port']}"
                    if self.check_proxy(ip_port):
                        return ip_port
                    else:
                        print(f"Proxy {ip_port} is not available.")
                        retries += 1
                        continue
                    # return ip_port
                else:
                    retries += 1
                    print(res.msg)
                    continue
            else:
                retries += 1
                if retries > max_retries:
                    print(f"Failed to get IP proxies after {max_retries} retries: {response.status_code}：{response.text}")
                    return False
                print(f"Request failed with status code {response.status_code}：{response.text}, retrying in 6 seconds...")
                time.sleep(6)  # 等待6秒后重试

# 使用示例
if __name__ == "__main__":
    # 初始化对象
    ip_proxy = ProxyIp(region=130100)

    # 获取IP代理
    ip_proxies = ip_proxy.tianqi_ip()
    print(ip_proxies)
